import styles from "./index.module.scss";
import type { Root } from "react-dom/client";
import { isClient } from "@/app/utils";
import { createRoot } from "react-dom/client";

const Loading: any = ({ style }) => {
  return (
    <div
      style={{
        position: "fixed",
        width: "100%",
        height: "100vh",
        zIndex: 1000,
        top: 0,
        left: 0,
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        background: "rgba(255,255,255,.5)",
        ...style,
      }}
    >
      <div className={styles.balls}>
        <div></div>
        <div></div>
        <div></div>
      </div>
      {/* <div className={styles.loading} style={style}></div> */}
    </div>
  );
};

let holderFragment: any = null;
let Loadings: any[] = [];
let root: Root;
function createContainer() {
  holderFragment = document.createElement("div");
  root = createRoot(holderFragment);
  document.body.appendChild(holderFragment);
}
function unmount() {
  root?.unmount();
  document.body.removeChild(holderFragment);
  holderFragment = null;
}
function open() {
  if (!isClient()) return;
  if (!holderFragment) {
    createContainer();
  }
  const key = Date.now();
  Loadings = [<Loading key={key} />];

  root.render(Loadings);
}

// let createLoading = { open, close: unmount };

Loading.open = open;
Loading.close = unmount;

export default Loading;
